package com.yilin.tms.data.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yilin.commons.exception.BusinessException;
import com.yilin.commons.util.ArrayUtil;
import com.yilin.commons.util.DateTimeUtil;
import com.yilin.tms.core.application.PageData;
import com.yilin.tms.core.commons.model.AuthData;

import com.yilin.tms.core.commons.utils.ParamUtil;
import com.yilin.tms.core.commons.utils.QueryUtil;
import com.yilin.tms.core.entity.data.contracted.ContractBody;
import com.yilin.tms.core.entity.order.goods.GoodsOrder;
import com.yilin.tms.core.entity.order.rob.RobOrder;
import com.yilin.tms.core.entity.order.transit.TransitOrder;
import com.yilin.tms.core.entity.truck.TruckVehicle;
import com.yilin.tms.core.entity.user.OrganType;
import com.yilin.tms.core.entity.user.RoleType;
import com.yilin.tms.core.entity.user.UserType;
import com.yilin.tms.core.entity.user.account.Account;
import com.yilin.tms.core.entity.user.organize.Organize;
import com.yilin.tms.data.mapper.ContractMapper;
import com.yilin.tms.data.service.IContractService;
import com.yilin.tms.core.remote.IOrderRemote;
import com.yilin.tms.core.remote.IUserRemote;
import com.yilin.tms.core.remote.IVehicleRemote;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.Date;

/**
 * 合同印章Service
 */
@Service
@Transactional
public class ContractService extends ServiceImpl<ContractMapper, ContractBody> implements IContractService {

    @Resource
    IOrderRemote orderRemote;
    @Resource
    IVehicleRemote vehicleRemote;
    @Resource
    IUserRemote userRemote;

    @Resource
    ContractMapper contractMapper;

    /**
     * 获取合同分页
     */
    @Override
    public PageData<ContractBody> getContractPage(Account loginUser, ContractBody query, Integer start, Integer limit) {
        QueryWrapper<ContractBody> queryWrapper = new QueryWrapper<>();
    if (loginUser.getUserType() == UserType.platformUser) {
            queryWrapper.eq("plat_id", loginUser.getOrganizeId());
        } else if (loginUser.getUserType() == UserType.shipperUser) {
            queryWrapper.ne("contract_state", ContractBody.ContractState.invalid.index);
            if (loginUser.getRoleType() == RoleType.manager) {
                queryWrapper.eq("pa_party_organize_id", loginUser.getOrganizeId());
            } else {
                queryWrapper.eq("pa_operate_account_id", loginUser.getId());
            }
        } else if (loginUser.getUserType() == UserType.truckerUser) {
            queryWrapper.ne("contract_state", ContractBody.ContractState.invalid.index);
            if (loginUser.getRoleType() == RoleType.manager) {
                queryWrapper.eq("pb_party_organize_id", loginUser.getOrganizeId())
                        .or().eq("pc_party_organize_id", loginUser.getOrganizeId());
            } else {
                queryWrapper.eq("pb_operate_account_id", loginUser.getId())
                        .or().eq("pc_operate_account_id", loginUser.getId());
            }
        }
        QueryUtil.andQueryWrapper(queryWrapper, query);
        return contractMapper.selectPage(new PageData<>(start, limit), queryWrapper);
    }

    /**
     * 获取生成电子合同
     */
    @Override
    public ContractBody saveOrGetTransitPromise(String transitOrderId) {
        ContractBody contractBody = contractMapper.selectOne(new QueryWrapper<ContractBody>().eq("transit_order_id", transitOrderId));
        if (contractBody != null) return contractBody;
        TransitOrder transitOrder = ParamUtil.isSuccess(orderRemote.getTransitOrderById(transitOrderId));
        if (transitOrder == null) throw new BusinessException("未查询到运单");
        RobOrder robOrder = ParamUtil.isSuccess(orderRemote.getRobOrderById(transitOrder.getRobOrderId()));
        GoodsOrder goodsOrder = ParamUtil.isSuccess(orderRemote.getGoodsOrderById(transitOrder.getGoodsOrderId()));
        TruckVehicle truckVehicle = ParamUtil.isSuccess(vehicleRemote.getVehicleById(transitOrder.getTransitTruckId()));
        Organize shipperOrganize = ParamUtil.isSuccess(userRemote.getOrganizeById(goodsOrder.getShipperOrganizeId()));
        //生成新的一份运单合同
        contractBody = new ContractBody();
        contractBody.setContractState(ContractBody.ContractState.going);
        contractBody.setMatchmaking(goodsOrder.getMatching());
        contractBody.setTransitOrderId(transitOrder.getId());
        contractBody.setShippingType(goodsOrder.getTransportTypeName());
        contractBody.setDeliveryNo(goodsOrder.getGoodsOrderNo());
        contractBody.setTransportNo(transitOrder.getTransportNo());
        contractBody.setTransportType(goodsOrder.getGoodsTypeName());
        contractBody.setAdditionalCost(goodsOrder.getShipperAdditionalCost());
        contractBody.setTotalCost(goodsOrder.getShipperTransportCost());
        contractBody.setInsuranceCost(goodsOrder.getInsuredCost());
        contractBody.setStartConsignorAddress(goodsOrder.getDisplayConsignorArea());
        contractBody.setEndConsigneeAddress(goodsOrder.getDisplayConsigneeArea());
        contractBody.setPromiseNo(DateTimeUtil.dateNo("HT"));
        contractBody.setTransportationCost(transitOrder.getAssignTransportCost());
        contractBody.setTruckNo(truckVehicle.getTrackNo());
        contractBody.setTruckUserName(transitOrder.getTransitTruckUserName());
        contractBody.setTruckUserPhone(transitOrder.getTransitTruckUserPhone());
//        contractBody.setOrganizeId(transitOrder.getor());
//        contractBody.setOrganizeName(transitOrder.getPlatName());
//        contractBody.setSuperiorPlatId(transitOrder.getZonePlatId());
//        contractBody.setSuperiorPlatName(transitOrder.getZonePlatName());
        contractBody.setCreateTime(new Date());
        //甲方信息
        contractBody.setPaPartyOrganizeId(goodsOrder.getShipperOrganizeId());
        contractBody.setPaPartyName(goodsOrder.getShipperOrganizeName());
        contractBody.setPaPartyPrincipal(transitOrder.getShipperAccountName());
        contractBody.setPaPartyPhone(transitOrder.getShipperAccountPhone());
        if (!contractBody.getMatchmaking()) {
            ///平台默认自动确认
//            Organize platform = userRemote.getOrganizeById(goodsOrder.get()).getData();
//            if (platform.getSignatureImg() == null) throw new BusinessException("平台印章信息未设置");
//            contractBody.setPbPartyOrganizeId(platform.getId());
//            contractBody.setPbPartyName(platform.getOrganizeName());
//            contractBody.setPbPartyPrincipal(platform.getManagerUserName());
//            contractBody.setPbPartyPhone(platform.getManagerUserPhone());
//            contractBody.setPbPartySign(platform.getSignatureImg());
//            contractBody.setPbSureTime(DateTimeUtil.dateToString(new Date(), "yyyy年MM月dd日 HH:mm:ss"));
            //丙方 车主
            contractBody.setPcPartyOrganizeId(robOrder.getRobOrganizeId());
            contractBody.setPcPartyName(robOrder.getRobOrganizeName());
            contractBody.setPcPartyPrincipal(robOrder.getRobAccountName());
            contractBody.setPcPartyPhone(robOrder.getRobAccountPhone());
        } else {
            //撮合两方合同 乙方为车主
            contractBody.setPbPartyOrganizeId(robOrder.getRobOrganizeId());
            contractBody.setPbPartyName(robOrder.getRobOrganizeName());
            contractBody.setPbPartyPrincipal(robOrder.getRobAccountName());
            contractBody.setPbPartyPhone(robOrder.getRobAccountPhone());
        }
        contractMapper.insert(contractBody);
        return contractBody;
    }

    /**
     * 签订合同
     */
    @Override
    public void signTransitPromise(Account loginUser, String transitOrderId, Organize organize) {
        ContractBody contractBody = saveOrGetTransitPromise(transitOrderId);
        AuthData.AuthItem[] authItems = ArrayUtil.initArr(AuthData.AuthItem.authPersonalSignetStamp);
        if (organize.getOrganType() != OrganType.individual) authItems = ArrayUtil.initArr(AuthData.AuthItem.authCompanySealStamp);
        ParamUtil.isSuccess(userRemote.checkAuthStatus(organize.getManagerUserId(), authItems));
        if (organize.getUserType() == UserType.shipperUser) {
            contractBody.setPaPartySign(organize.getSignatureImg());
            contractBody.setPaSureTime(DateTimeUtil.dateToString(new Date(), "yyyy年MM月dd日 HH:mm:ss"));
            contractBody.setPaOperateAccountId(loginUser.getId());
        } else if (organize.getUserType() == UserType.truckerUser) {
            if (contractBody.getMatchmaking()) {
                contractBody.setPbPartySign(organize.getSignatureImg());
                contractBody.setPbSureTime(DateTimeUtil.dateToString(new Date(), "yyyy年MM月dd日 HH:mm:ss"));
                contractBody.setPbOperateAccountId(loginUser.getId());
            } else {
                contractBody.setPcPartySign(organize.getSignatureImg());
                contractBody.setPcSureTime(DateTimeUtil.dateToString(new Date(), "yyyy年MM月dd日 HH:mm:ss"));
                contractBody.setPcOperateAccountId(loginUser.getId());
            }
            contractBody.setContractState(ContractBody.ContractState.success);
        }
        contractBody.setUpdateTime(new Date());
        contractMapper.updateById(contractBody);
    }

}
